#!/bin/sh

###
# replacement for "install", which is missing, when BSD-Tools are not installed
# call: installfile( src, dest, mode, owner, group )
###

installfile()
{
   cp -f "$1" "$2"
   chown "$4" "$2"
   chgrp "$5" "$2"
   chmod "$3" "$2"
}

###
# replacement for "install", which is missing, when BSD-Tools are not installed
# call: installdir( newdir, owner, group )
###

installdir()
{
  if [ ! -d "$1" ]; then
    # if directory already exists leave it untouched
    mkdir "$1"
    chown "$2" "$1"
    chgrp "$3" "$1"
  fi
}
  
usage()
{
  echo "usage: $0 <srcdir>"
  echo "       <srcdir> containing files to be installed"
  echo "                (aksusbd, Aladdin, StartupParameters.plist)"
}


###
# Improvision additions
###

# We remove the old drivers - old installers put these in /System/Library/StartupItems
# this is not a good place for them to be.
echo "Removing old Aladdin drivers"
rm -rf /System/Library/StartupItems/Aladdin

# Now make sure that the directory where all our files are and install
echo "Running Aladdin installer"
cd "$1/Contents/Resources"


###
# Install the Aladdin daemon
###

if [ $(uname -s) != "Darwin" ]; then
	echo "Not running on Darwin/MacOSX -- aborted!"
	exit 1
fi

if [ "$EUID" != "0" ]; then
  echo "Must be run as root"
  exit 1
fi

srcdir="./"
startup=Aladdin
startupitems=/Library/StartupItems/
startdir=${startupitems}${startup}/

if [ ! -f "${srcdir}/Aladdin" ]; then
  echo "file 'Aladdin' missing in '${srcdir}'"
  usage $0
  exit 2
fi

if [ ! -f "${srcdir}/StartupParameters.plist" ]; then
  echo "file 'StartupParameters.plist' missing in '${srcdir}'"
  usage $0
  exit 2
fi

if [ ! -f "${srcdir}/aksusbd" ]; then
  echo "file 'aksusbd' missing in '${srcdir}'"
  usage $0
  exit 2
fi

echo "---------------------------------------"
echo "Copy Aladdin USB daemon to /usr/libexec/aksusbd ..."

installfile "${srcdir}/aksusbd" "/usr/libexec/aksusbd" 555 root wheel

echo "Create directory ${startdir} and copy plist ..."
installdir "${startupitems}" root wheel
installdir ${startdir} root wheel
installfile "${srcdir}/StartupParameters.plist" ${startdir}StartupParameters.plist 444 root wheel

echo "Copy startup file ..."
installfile "${srcdir}/${startup}" ${startdir}${startup} 755 root wheel

###
# In some cases the following commands can't be executed,
# because some of the BSD-tools used might not be installed
###

if [ -f /usr/bin/sed ]; then
   echo "Try to start daemon ... "
   ps axh | grep aksusbd | grep -v grep | grep -v dinst

   dpid=$(ps axh | grep aksusbd | grep -v grep | grep -v dinst | sed 's/ *\(.*\)/\1/' |  cut -f1 -d\  | head -1)

   if [ -n "$dpid" ]; then
	   echo "Killing already running aksusbd with PID" $dpid
	   kill $dpid
	   sleep 2
   fi

   ${startdir}${startup}
   echo Done
else
   echo "Reboot necessary to start the new daemon!"
fi